// 添加返回首页按钮事件
document.querySelector(".home-btn").addEventListener("click", () => {
  window.location.href = "/";
});
// 全局变量
let socket;
let videoFilePath = "";
let videoFileName = "";
let autoScroll = true;

// 初始化Socket.io连接
function initSocket() {
  console.log("Initializing socket connection...");
  socket = io();

  // 确保只绑定一次事件
  socket.off("status_update");
  socket.off("stream_log");
  socket.off("connect");
  socket.off("disconnect");
  socket.off("connect_error");

  socket.on("connect", function () {
    console.log("Socket connected successfully");
    addLogEntry("js: 已连接到服务器");
  });

  socket.on("disconnect", function () {
    console.log("Socket disconnected");
  });

  socket.on("connect_error", function (err) {
    console.error("Socket connection error:", err);
  });

  socket.on("status_update", function (data) {
    console.log("Received status update:", data);

    // 确保正确处理布尔值
    const pushing = !!data.pushing;
    const pulling = !!data.pulling;

    updatePushStatus(pushing);
    updatePullStatus(pulling);
  });

  socket.on("stream_log", function (data) {
    console.log("Received log message:", data.message);
    if (data.message) addLogEntry(`js: ${data.message}`);
  });
}

// 更新推流状态
function updatePushStatus(isActive) {
  const statusElem = document.getElementById("pushStatus");
  const btn = document.getElementById("pushBtn");
  const animation = document.getElementById("pushAnimation");

  // 确保按钮元素存在
  if (!btn) {
    console.error("Push button element not found");
    return;
  }

  // 确保按钮状态正确更新
  const isCurrentlyActive = btn.innerHTML.includes("停止");

  // 只有当状态变化时才更新
  if (isActive && !isCurrentlyActive) {
    statusElem.innerHTML =
      '<span class="status-indicator status-active"></span><span>运行中</span>';
    btn.innerHTML = '<i class="bi bi-stop-circle me-2"></i>停止推流';
    btn.classList.replace("btn-success", "btn-danger");
    if (animation) animation.classList.add("visible");
  } else if (!isActive && isCurrentlyActive) {
    statusElem.innerHTML =
      '<span class="status-indicator status-inactive"></span><span>未运行</span>';
    btn.innerHTML = '<i class="bi bi-play-circle me-2"></i>开始推流';
    btn.classList.replace("btn-danger", "btn-success");
    if (animation) animation.classList.remove("visible");
  }

  // 调试日志
  console.log(`updatePushStatus: ${isActive} | Button text: ${btn.innerText}`);

  updateButtonStates();
}

// 更新拉流状态
function updatePullStatus(isActive) {
  const statusElem = document.getElementById("pullStatus");
  const btn = document.getElementById("pullBtn");
  const animation = document.getElementById("pullAnimation");

  if (isActive) {
    statusElem.innerHTML =
      '<span class="status-indicator status-active"></span><span>运行中</span>';
    btn.innerHTML = '<i class="bi bi-stop-circle me-2"></i>停止拉流';
    btn.classList.replace("btn-warning", "btn-danger");
    animation.classList.add("visible");
  } else {
    statusElem.innerHTML =
      '<span class="status-indicator status-inactive"></span><span>未运行</span>';
    btn.innerHTML = '<i class="bi bi-play-circle me-2"></i>开始拉流';
    btn.classList.replace("btn-danger", "btn-warning");
    animation.classList.remove("visible");
  }
  updateButtonStates();
}

function addLogEntry(message) {
  const now = new Date();
  const timestamp = now.toTimeString().split(" ")[0]; // HH:MM:SS 格式
  const logContainer = document.getElementById("logContainer");
  const logEntry = document.createElement("div");
  logEntry.className = "log-entry";

  // 添加时间戳
  const timeSpan = document.createElement("span");
  timeSpan.className = "log-timestamp";
  timeSpan.textContent = `[${timestamp}] `;
  timeSpan.style.color = "#5bc0de";

  // 添加消息内容
  const messageSpan = document.createElement("span");
  messageSpan.className = "log-message";
  messageSpan.textContent = message;

  logEntry.appendChild(timeSpan);
  logEntry.appendChild(messageSpan);
  logContainer.appendChild(logEntry);
  if (autoScroll) {
    logContainer.scrollTop = logContainer.scrollHeight;
  }
  matchRightCardHeight();
}

// 处理文件上传
function handleFileUpload(file) {
  document.getElementById("fileName").textContent = file.name;
  document.getElementById("fileInfo").classList.remove("d-none");

  const formData = new FormData();
  formData.append("file", file);

  addLogEntry(
    `js: 正在上传视频文件: ${file.name} (${(file.size / 1024 / 1024).toFixed(
      2
    )} MB)`
  );

  fetch("/upload_video", {
    method: "POST",
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.status === "success") {
        videoFilePath = data.file_path;
        videoFileName = data.filename;
        addLogEntry(`js: 视频文件上传成功: ${videoFileName}`);
      } else {
        addLogEntry(`js: 文件上传失败: ${data.message}`);
      }
    })
    .catch((error) => {
      addLogEntry(`js: 文件上传错误: ${error.message}`);
    })
    .finally(() => {
      document.getElementById("videoFile").value = "";
      updateButtonStates();
    });
}

// 更新按钮状态
function updateButtonStates() {
  const pushBtn = document.getElementById("pushBtn");
  const pullBtn = document.getElementById("pullBtn");
  const isPushing = pushBtn.innerHTML.includes("停止");
  const isPulling = pullBtn.innerHTML.includes("停止");

  // 获取当前设置
  const pushProtocol = document.querySelector(
    'input[name="pushProtocol"]:checked'
  )?.value;
  const rtpMode =
    pushProtocol === "RTP"
      ? document.querySelector('input[name="rtpMode"]:checked')?.value
      : null;
  const isWvp = pushProtocol === "RTP" && rtpMode === "wvp";

  // 重置按钮状态
  pushBtn.disabled = false;
  pullBtn.disabled = false;
  pushBtn.title = "";
  pullBtn.title = "";

  // 处理推流按钮状态
  pushBtn.disabled = false;
  if (isWvp) {
    pushBtn.title = "点击显示WVP模式提示";
  } else {
    pushBtn.title = !videoFilePath ? "请先上传视频文件" : "";
  }

  // 处理拉流按钮状态
  pullBtn.disabled = false;
  pullBtn.title = "";

  // WVP模式下检查设备ID和通道ID
  const wvpPushProtocol = document.querySelector(
    'input[name="pushProtocol"]:checked'
  )?.value;
  const wvpRtpMode =
    wvpPushProtocol === "RTP"
      ? document.querySelector('input[name="rtpMode"]:checked')?.value
      : null;
  const isWvpMode = wvpPushProtocol === "RTP" && wvpRtpMode === "wvp";

  if (isWvpMode) {
    const deviceId = document.getElementById("deviceId").value;
    const channelId = document.getElementById("channelId").value;
    if (!deviceId || !channelId) {
      pullBtn.title = "请填写设备ID和通道ID";
    }
  }
}

function updateRtpSettings() {
  const pushProtocol = document.querySelector(
    'input[name="pushProtocol"]:checked'
  )?.value;
  const isRtp = pushProtocol === "RTP";
  const rtpMode = isRtp
    ? document.querySelector('input[name="rtpMode"]:checked')?.value
    : null;
  const isWvp = isRtp && rtpMode === "wvp";

  const rtpSettings = document.getElementById("rtpSettings");
  const wvpSettings = document.getElementById("wvpSettings");
  const deviceIdInput = document.getElementById("deviceId");
  const channelIdInput = document.getElementById("channelId");
  const wvpTip = document.getElementById("wvpTip");

  // RTP设置区域在非RTP协议时变灰
  rtpSettings.style.opacity = isRtp ? "1" : "0.5";

  // local/wvp切换按钮在非RTP协议时禁用
  document
    .querySelectorAll('input[name="rtpMode"]')
    .forEach((radio) => (radio.disabled = !isRtp));

  // 设备ID和通道ID仅在wvp模式时可编辑
  deviceIdInput.disabled = !isWvp;
  channelIdInput.disabled = !isWvp;
  wvpTip.style.display = isWvp ? "inline" : "none";

  // 更新按钮状态
  updateButtonStates();
}

// 开始推/拉流
function startStream(streamType) {
  const serverAddress = document.getElementById("serverAddress").value;
  const streamCount =
    parseInt(document.getElementById("streamCount").value) || 1;

  const formData = {
    stream_type: streamType,
    server_address: serverAddress,
    stream_count: streamCount,
  };
  if (formData.loop_mode) {
    document.getElementById("loopStatus").innerText = `进行中 (${
      i + 1
    }/${loop_count})`;
  }
  if (streamType === "push") {
    if (!videoFilePath) {
      addLogEntry("js: 请先上传视频文件");
      return;
    }

    formData.push_protocol = document.querySelector(
      'input[name="pushProtocol"]:checked'
    ).value;
    formData.video_path = videoFilePath;

    if (formData.push_protocol === "RTP") {
      formData.rtp_mode = document.querySelector(
        'input[name="rtpMode"]:checked'
      ).value;
      if (formData.rtp_mode === "wvp") {
        formData.device_id = document.getElementById("deviceId").value;
        formData.channel_id = document.getElementById("channelId").value;
      }
    }
  } else {
    // ✅ 拉流逻辑（原来漏了 push_protocol/rtp_mode）
    formData.pull_protocol = document.querySelector(
      'input[name="pullProtocol"]:checked'
    ).value;
    formData.pull_mode = document.querySelector(
      'input[name="pullMode"]:checked'
    ).value;

    formData.push_protocol = document.querySelector(
      'input[name="pushProtocol"]:checked'
    )?.value;
    formData.loop_mode = document.getElementById("loopModeToggle").checked;

    if (formData.loop_mode) {
      formData.loop_count = parseInt(
        document.getElementById("pullCount").value
      );
      formData.loop_duration = parseInt(
        document.getElementById("pullDuration").value
      );
      formData.loop_interval = parseInt(
        document.getElementById("pullInterval").value
      );
    }
    formData.rtp_mode =
      formData.push_protocol === "RTP"
        ? document.querySelector('input[name="rtpMode"]:checked')?.value
        : null;

    if (formData.push_protocol === "RTP" && formData.rtp_mode === "wvp") {
      formData.device_id = document.getElementById("deviceId").value;
      formData.channel_id = document.getElementById("channelId").value;
    } else {
      formData.video_path = videoFilePath;
    }
  }

  // 发送请求
  fetch("/start_stream", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(formData),
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.status === "success") {
        addLogEntry(`js: ${data.message}`);
        if (streamType === "pull") {
          updatePullStatus(true);
        }
      } else {
        addLogEntry(`js: 启动${streamType}失败: ${data.message}`);
        if (streamType === "push") updatePushStatus(false);
        else updatePullStatus(false);
      }
    })
    .catch((error) => {
      addLogEntry(`js: 启动${streamType}失败: ${error.message}`);
      if (streamType === "push") updatePushStatus(false);
      else updatePullStatus(false);
    });
}

// 停止推/拉流
function stopStream(streamType) {
  fetch("/stop_stream", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ stream_type: streamType }),
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.status === "success") {
        // 只在这里记录停止消息
        addLogEntry(`js: ${data.message}`);
      } else {
        addLogEntry(`js: 停止${streamType}失败: ${data.message}`);
      }
    })
    .catch((error) => {
      addLogEntry(`js: 停止${streamType}失败: ${error.message}`);
    });
}

// 初始化事件监听器
function initEventListeners() {
  // 文件上传
  document.getElementById("uploadBtn").addEventListener("click", () => {
    document.getElementById("videoFile").click();
  });

  document.getElementById("videoFile").addEventListener("change", (e) => {
    if (e.target.files.length > 0) {
      const file = e.target.files[0];
      const validTypes = ["video/mp4", "video/avi", "video/quicktime"];
      if (!validTypes.includes(file.type)) {
        addLogEntry("js: 错误：仅支持MP4、AVI、MOV格式的视频文件");
        return;
      }
      handleFileUpload(file);
    }
  });

  // RTP设置
  document.querySelectorAll('input[name="pushProtocol"]').forEach((radio) => {
    radio.addEventListener("change", updateRtpSettings);
  });

  document.querySelectorAll('input[name="rtpMode"]').forEach((radio) => {
    radio.addEventListener("change", updateRtpSettings);
  });
  const loopToggle = document.getElementById("loopModeToggle");
  loopToggle.addEventListener("change", function () {
    const container = document.getElementById("loopSettings");
    const inputs = container.querySelectorAll("input");
    if (this.checked) {
      container.classList.remove("setting-disabled");
      inputs.forEach((i) => (i.disabled = false));
    } else {
      container.classList.add("setting-disabled");
      inputs.forEach((i) => (i.disabled = true));
    }
    updateButtonStates();
  });

  const logContainer = document.getElementById("logContainer");
  const scrollBtn = document.getElementById("scrollToBottomBtn");

  logContainer.addEventListener("scroll", () => {
    const atBottom =
      logContainer.scrollHeight - logContainer.scrollTop <=
      logContainer.clientHeight + 5;
    autoScroll = atBottom;

    // 切换按钮样式
    if (autoScroll) {
      scrollBtn.classList.add("active");
      scrollBtn.classList.remove("inactive");
    } else {
      scrollBtn.classList.add("inactive");
      scrollBtn.classList.remove("active");
    }
  });
  if (scrollBtn) {
    scrollBtn.addEventListener("click", () => {
      logContainer.scrollTop = logContainer.scrollHeight;
      autoScroll = true;
      scrollBtn.classList.add("active");
      scrollBtn.classList.remove("inactive");
    });
  }

  // 推流按钮
  document.getElementById("pushBtn").addEventListener("click", () => {
    const isPushing = document
      .getElementById("pushBtn")
      .innerHTML.includes("停止");
    const pushProtocol = document.querySelector(
      'input[name="pushProtocol"]:checked'
    )?.value;
    const rtpMode =
      pushProtocol === "RTP"
        ? document.querySelector('input[name="rtpMode"]:checked')?.value
        : null;
    const isWvp = pushProtocol === "RTP" && rtpMode === "wvp";

    if (isPushing) {
      stopStream("push");
      return;
    }

    if (isWvp) {
      addLogEntry("js: WVP模式无需推流，请直接使用设备ID和通道ID进行拉流");
      return;
    }

    if (!videoFilePath) {
      addLogEntry("js: 请先上传视频文件");
      return;
    }

    startStream("push");
  });

  // 拉流按钮
  document.getElementById("pullBtn").addEventListener("click", () => {
    const isPulling = document
      .getElementById("pullBtn")
      .innerHTML.includes("停止");
    if (isPulling) {
      stopStream("pull");
      return;
    }

    // WVP模式下检查设备ID和通道ID
    const pushProtocol = document.querySelector(
      'input[name="pushProtocol"]:checked'
    )?.value;
    const rtpMode =
      pushProtocol === "RTP"
        ? document.querySelector('input[name="rtpMode"]:checked')?.value
        : null;
    const isWvp = pushProtocol === "RTP" && rtpMode === "wvp";

    if (isWvp) {
      const deviceId = document.getElementById("deviceId").value;
      const channelId = document.getElementById("channelId").value;
      if (!deviceId || !channelId) {
        addLogEntry("js: 请先填写设备ID和通道ID");
        return;
      }
    } else {
      const isPushing = document
        .getElementById("pushBtn")
        .innerHTML.includes("停止");
      if (!isPushing) {
        addLogEntry("js: 请先开始推流");
        return;
      }
    }

    startStream("pull");
  });

  // 其他按钮
  document.getElementById("openTerminalBtn").addEventListener("click", () => {
    addLogEntry("js: 正在打开终端...");
    fetch("/open_terminal", { method: "POST" })
      .then((response) => response.json())
      .then((data) => addLogEntry(`js: ${data.message}`))
      .catch((error) => addLogEntry(`js: 打开终端失败: ${error.message}`));
  });

  document.getElementById("clearLogBtn").addEventListener("click", () => {
    document.getElementById("logContainer").innerHTML = "";
    addLogEntry("js: 日志已清空");
  });

  document.getElementById("clearTempBtn").addEventListener("click", () => {
    fetch("/clear_temp", { method: "POST" })
      .then((response) => response.json())
      .then((data) => {
        if (data.status === "success") {
          addLogEntry("js: 临时文件已清理");
        }
      });
  });
}

function matchRightCardHeight() {
  const left = document.getElementById("leftCard");
  const right = document.getElementById("rightCard");
  if (left && right) {
    const leftHeight = left.offsetHeight;
    right.style.height = leftHeight + "px";
  }
}

function initTooltips() {
  const tooltipTriggerList = [].slice.call(
    document.querySelectorAll('[data-bs-toggle="tooltip"]')
  );
  tooltipTriggerList.forEach((tooltipTriggerEl) => {
    new bootstrap.Tooltip(tooltipTriggerEl);
  });
}

window.addEventListener("load", () => {
  matchRightCardHeight();
  // 防止字体渲染延迟导致高度出错
  setTimeout(matchRightCardHeight, 100);
});

window.addEventListener("resize", matchRightCardHeight);

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", () => {
  initSocket();
  initEventListeners();
  updateRtpSettings(); // 初始化RTP设置状态
  initTooltips();
  addLogEntry("js: 推拉流工具已启动");
  addLogEntry("js: 请配置服务器地址和媒体文件");
});
